# 正则表达式练习
import  re


# 正则表达式的简单用法
def easy():
    # 邮箱地址的正则校验
    result = re.search(r"\w+?@\w+?\.com", "mofan@mofanpy.com")
    print(result)
    # 手机号的正则校验：   以非0开头的11位数字
    result = re.search(r"^[1-9]\d{10}", "15991608252")
    print(result)


# 提前编译的方式使用正则表达式
def bianyi():

    pattern = re.compile(r"^Hello")
    print(pattern.search("hello"))
    print(pattern.search("Hello"))
    print(pattern.search("hHello"))


# 从模式中获取信息
def getInfoFromPattern():
    found = []
    for i in re.finditer(r"[\w-]+?\.jpg", "I have 2021-02-01.jpg, 2021-02-02.jpg, 2021-02-03.jpg"):
        print(i)
        a=i.group()
        found.append(re.sub(r".jpg", "", i.group()))
    print(found)

    # 通过(pattern)可以直接获取某一部分匹配
    string = "I have 2021-02-01.jpg, 2021-02-02.jpg, 2021-02-03.jpg"
    print("without ():", re.findall(r"[\w-]+?\.jpg", string))
    print("with ():", re.findall(r"([\w-]+?)\.jpg", string))

    """" 分开获取不同的信息,可以多用几个括号
    然后用 group 功能获取到不同括号中匹配到的字符串。"""
    string = "I have 2021-02-01.jpg, 2021-02-02.jpg, 2021-02-03.jpg"
    match = re.finditer(r"(\d+?)-(\d+?)-(\d+?)\.jpg", string)
    for file in match:
        print("matched string:", file.group(0), ",year:", file.group(1), ", month:", file.group(2), ", day:",
              file.group(3))

    """findall 也可以达到同样的目的。只是它没有提供 file.group(0) 这种全匹配的信息。"""
    string = "I have 2021-02-01.jpg, 2021-02-02.jpg, 2021-02-03.jpg"
    match = re.findall(r"(\d+?)-(\d+?)-(\d+?)\.jpg", string)
    for file in match:
        print("year:", file[0], ", month:", file[1], ", day:", file[2])

    """还能用一个名字来索引匹配好的字段， 然后用 group("索引") 的方式获取到对应的片段。"""
    string = "I have 2021-02-01.jpg, 2021-02-02.jpg, 2021-02-03.jpg"
    match = re.finditer(r"(?P<y>\d+?)-(?P<m>\d+?)-(?P<d>\d+?)\.jpg", string)
    for file in match:
        print("matched string:", file.group(0),
              ", year:", file.group("y"),
              ", month:", file.group("m"),
              ", day:", file.group("d"))

if __name__ == '__main__':
    #easy()
    # bianyi()
    getInfoFromPattern()